<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//引入Stream模型
use App\Http\Models\Stream;
use Illuminate\Support\Facades\Validator;


class StreamController extends Controller
{
    /**
     * 直播流列表显示
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(){
        $data = Stream::get();
        return view('admin/stream/index',compact('data'));
    }

    public function add(Request $request){

        if($request->isMethod('post')){
            $data = $request->all();
            $rules = [
                'stream_name'=>'required|unique:stream,stream_name',
            ];
            $notices = [
                'stream_name.required'=>'直播流名不能为空',
                'stream_name.unique'=>'直播流名已存在'
            ];
            $validator = Validator::make($data,$rules,$notices);
            if($validator->passes()){
                Stream::create($data);
                return ['success'=>true];
            }else{
                $errorInfo = collect($validator->messages())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorInfo];
            }

        }elseif($request->isMethod('get')){
            return view('admin/stream/add');
        }

    }

    //删除直播流名
    public function del(Request $request,Stream $stream){
        $res = $stream->delete();
        if($res){
            return ['success'=>true];
        }else{
            return ['success'=>false];
        }
    }

    //编辑直播流名
    public function edit(Request $request,Stream $stream){
        if($request->isMethod('post')){
//            dd($request->input('stream_name'));
            $data = $request->all();
            $rules = [
                'stream_name'=>'required|unique:stream,stream_name',
            ];
            $notices = [
                'stream_name.required'=>'直播流名不能为空',
                'stream_name.unique'=>'直播流名已存在'
            ];
            $validator = Validator::make($data,$rules,$notices);
            if($validator->passes()){
                $res = $stream->update($data);
                if($res === false){
                    return ['success'=>false,'errorinfo'=>'数据修改失败'];
                }elseif($res ===0){
                    return ['success'=>false,'errorinfo'=>'不能和修改前一样'];
                }else{
                    return ['success'=>true];
                }
            }else{
                //将数组变为集合 再讲集合连接成字符串
                $errorInfo = collect($validator->errors())->implode('0','|');
                return ['success'=>false,'errorinfo'=>$errorInfo];
            }
        }
//        dd($stream);
        return view('admin.stream.edit',compact('stream'));
    }
}
